package com.ainiyar.springweb.config.security.service;

import com.ainiyar.springweb.pojo.entity.Admin;
import com.ainiyar.springweb.pojo.entity.Menu;
import com.ainiyar.springweb.pojo.entity.Role;
import com.ainiyar.springweb.service.AdminService;
import com.ainiyar.springweb.service.MenuService;
import com.ainiyar.springweb.service.RoleService;
import jakarta.annotation.Resource;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;

/**************************************
 * File Name : CustomerAdminDetailsService
 * Created with : IntelliJ IDEA.
 * Author : 艾尼亚尔·毛拉吾提
 * QQ : 524155792  WeChat : ainiyar0124
 * Created Time : 2024/2/4  18:05
 * Desc :登录
 ***************************************/
@Component
public class CustomerAdminDetailsService implements UserDetailsService {
    @Resource
    private AdminService adminService;
    @Resource
    private MenuService menuService;
    @Resource
    private RoleService roleService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Admin admin=adminService.findAdminByAccount(username);
        if (admin==null){
            throw new RuntimeException("账号或密码错误、登录失败！");
        }
        //查询当前登录用户拥有的权限列表
        List<Menu> permissionList;
        if (admin.getIsSupper()==1){
            permissionList=menuService.findPermissionListForSuperSuperAdmin();
        }else {
            //判断当前账号所属的角色状态
            Role role=roleService.getRoleByAdminRoleId(Long.valueOf(admin.getRoleId()));
            if (role.getStatus()==0){
                throw new RuntimeException("登录失败、当前账号所属的角色已停用！");
            }
            permissionList=menuService.findPermissionListByAdminId(admin.getId());
        }
        //获取对应的权限编码
        List<String> codeList = permissionList.stream().filter(Objects::nonNull)
                .map(Menu::getCode)
                .filter(Objects::nonNull)
                .toList();
        //将权限编码列表转换成数组
        String[] strings = codeList.toArray(new String[codeList.size()]);
        List<GrantedAuthority> authorityList = AuthorityUtils.createAuthorityList(strings);
        //将权限列表设置给admin对象
        admin.setAuthorities(authorityList);
        //设置该管理员拥有的菜单信息
        admin.setPermissionList(permissionList);
        //查询成功
        return admin;
    }
}

